import { observable, action } from 'mobx';
import { message } from 'antd';
import { ResponseException } from '~/plugins/axios';

interface ErorrPopupItem {
  err: Error
  id: number
  msg?: string
}

const state = observable({
  errors: [] as Array<ErorrPopupItem>,
  snackBarErrors: [] as Array<ErorrPopupItem>,
});

let id = 0;

const showErrorPopup = action((err: Error, msg?: string) => {
  state.errors.push({
    err,
    id,
    msg,
  });
  id += 1;
});

const showErrorSnackbar = action((err: Error, msg?: string) => {
  state.snackBarErrors.push({
    err,
    id,
    msg,
  });
  id += 1;
});

const closeErrorPopup = action((item: ErorrPopupItem) => {
  const index = state.errors.indexOf(item);
  if (index !== -1) {
    state.errors.splice(index, 1);
  }
});

const api = (err: unknown) => {
  if (err instanceof ResponseException) {
    // TODO: error message parse and display
    message.error(err.res?.error ?? 'error');
  } else if (err instanceof Error) {
    // TODO:
  }

  // TODO:
};

export const errorService = {
  state,
  showErrorPopup,
  closeErrorPopup,
  showErrorSnackbar,
  api,
};
